import { defineStore } from 'pinia'
import audioPlayer from '@/common/AudioPlayer';
import { MediaStatus } from '@/common/const'
import type { IcyData, Station } from '@/common/types/interface'
import { getRandomStations } from '@/common/station_api'
type SwitchBehavior = 'userClick' | 'prevNext' | 'replace';
const defaultStation = {
	"stationuuid": "388756ad-5abd-45cd-bc99-50a6b79e92b8",
	"name": "新闻听天下",
	"url": "https://lhttp.qtfm.cn/live/20500169/64k.mp3",
	"country": "China",
	"language": "Chinese",
	"favicon": "https://pic.qtfm.cn/2023/0209/20230209061451.png"
} as Station;
const MAX_PLAYLIST_LENGTH = 10;
export const usePlayerStore = defineStore('playerStore', {
	state: () => ({
		status: MediaStatus.stoped,
		playError: false,
		playIndex: -1,
		currentRadio: null as unknown as Station,
		icyData: null as unknown as IcyData,
		volume: 1,
		autoPlay: false,
		histories: [] as { id: number; station: Station }[],
		favorites: [] as Station[],
		playList: [] as Station[]
	}),
	getters: {

	},
	actions: {
		play() {
			this.status = MediaStatus.waiting
			this.playError = false;
			audioPlayer.onStatusChange = (status: MediaStatus) => {
				console.log('audioPlayer的状态改变事件:', status);
				this.status = status;
				this.playError = status === MediaStatus.error;
			}
			audioPlayer.play(this.currentRadio);

			// #ifdef APP-PLUS
			const AudioNotification = uni.requireNativePlugin("Audio-Notification");
			AudioNotification.play();
			// #endif
		},

		pause() {
			audioPlayer.pause()
			this.status = MediaStatus.paused
		},

		stop() {
			audioPlayer.stop()
			this.status = MediaStatus.stoped

			// #ifdef APP-PLUS
			const AudioNotification = uni.requireNativePlugin("Audio-Notification");
			AudioNotification.pause();
			// #endif
		},


		switchStation(station: Station, behavior: SwitchBehavior = 'userClick') {
			console.log(station.url);
			if (this.currentRadio && station.stationuuid === this.currentRadio?.stationuuid) {
				if (this.status !== MediaStatus.playing) this.play();
				return;
			}

			if (!station.favicon) station.favicon = `/static/radios/${Math.floor(Math.random() * 10) + 1}.jpg`;
			this.status = MediaStatus.switching;
			this.icyData = { song: '', cover: '' };
			// this.stop();
			this.currentRadio = station;
			this.addToHistory(station);

			// 只有用户点击才插入到播放列表
			if (behavior === 'userClick') {
				this.addToPlayList(station);
				this.playIndex = Math.min(MAX_PLAYLIST_LENGTH - 1, this.playIndex + 1)
			}

			this.play();
		},

		addToPlayList(station: Station) {
			this.playList.splice(this.playIndex + 1, 0, station);
			if (this.playList.length > MAX_PLAYLIST_LENGTH) {
				this.playList.shift(); // 超出最大长度时自动移除第一条
			}
		},
		addToHistory(station: Station) {
			this.histories.push(({
				id: Date.now(),
				station
			}))
		},
		removeHistory(id: number) {
			const idx = this.histories.findIndex(e => e.id === id);
			if (idx !== -1) this.histories.splice(idx, 1);
		},
		toggleFavorite(station: Station) {
			const idx = this.favorites.findIndex(e => e.stationuuid === station.stationuuid);
			if (idx === -1) this.favorites.push(station); else this.favorites.splice(idx, 1);
		},

		setAutoPlay(autoPlay: boolean) {
			this.autoPlay = autoPlay;
			// audioPlayer.autoPlay = autoPlay;
			// if (autoPlay && this.status !== MediaStatus.playing) this.play();
		},

		next() {
			const idx = this.playIndex + 1;
			if (idx >= this.playList.length) {
				getRandomStations(1).then(res => {
					this.switchStation(res[0], 'userClick'); // 随机播放也可以视为用户行为
				}).catch(console.log);
			} else {
				this.playIndex = idx;
				this.switchStation(this.playList[idx], 'prevNext');
			}
		},

		prev() {
			const idx = this.playIndex - 1;
			if (idx < 0) {
				uni.showToast({ title: '已经是第一个了', icon: 'none' });
				return;
			}
			this.playIndex = idx;
			this.switchStation(this.playList[idx], 'prevNext');
		}

	},
	unistorage: true
})